import 'package:flutter/material.dart';
import 'package:flutter_chat/common/constant/router_name.dart';
import 'package:flutter_chat/common/utils/log.dart';
import 'package:flutter_chat/common/utils/string.dart';
import 'package:get/get.dart';

import 'logic.dart';

class LoginPage extends GetView<LoginLogic> {
  const LoginPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("登录"),
      ),
      body: Form(
          key: controller.formKey,
          onChanged: () {
            LogUtils.println("验证表单");
            // 验证表单
            controller.formKey.currentState!.validate();
          },
          child: Stack(
            alignment: AlignmentDirectional.bottomCenter,
            children: [
              ListView(
                padding: EdgeInsets.all(40),
                physics: const BouncingScrollPhysics(
                  parent: AlwaysScrollableScrollPhysics(),
                ),
                children: [
                  _buildUsername(),
                  _buildPassword(),
                  const SizedBox(
                    height: 80,
                  ),
                  _buildLogin(),
                ],
              ),
              Positioned(
                  bottom: 20,
                  child: TextButton(
                    onPressed: () {
                      Get.toNamed(RouterName.register,
                          arguments: {"name": "111"});
                    },
                    child: Text(
                      "还没有账号，去注册",
                      style: TextStyle(color: Colors.blue),
                    ),
                  ))
            ],
          )),
    );
  }

  ElevatedButton _buildLogin() {
    return ElevatedButton(
        onPressed: () {
          // 表单校验通过才会继续执行
          if (controller.formKey.currentState!.validate()) {
            Get.back();
            //TODO 执行登录方法
            LogUtils.println(
              'email: ${controller.state.loginData["username"]}, password: ${controller.state.loginData["password"]}',
            );
          }
        },
        child: Container(
          alignment: Alignment.center,
          height: 50,
          child: const Text('登录'),
        ));
  }

  TextFormField _buildUsername() {
    return TextFormField(
      decoration: const InputDecoration(labelText: '用户名'),
      validator: (v) {
        if (StringUtils.hasEmpty(v)) {
          return "请填写用户名";
        }
      },
      onChanged: (value) {
        controller.updateLoginData("username", value);
      },
    );
  }

  TextFormField _buildPassword() {
    return TextFormField(
      decoration: const InputDecoration(labelText: '密码'),
      obscureText: true,
      validator: (v) {
        if (StringUtils.hasEmpty(v)) {
          return "请填写密码";
        }
      },
      onChanged: (value) {
        controller.updateLoginData("password", value);
      },
    );
  }
}
